/**
 * Description：入库申请 hooks
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer：朱楠
 * date: 2024.8.15
 */
const { ref, reactive } = Vue
import { useFetch } from '../../../Scripts/hooks/useFetch.js'
const { ElMessage, ElMessageBox } = ElementPlus
import { useCommon } from '../useCommon.js';

export function useInstore() {
  const baseAPI = '../../../Ashx/ContainerInstoreVue3PageHandler.ashx';

  const { getFactoryListByCode, generateUUID } = useCommon();
  let currentUserInfo = {};// 当前登录用户信息

  const instoreObjFormRef = ref(null);//表单ref
  const instoreObjTableRef = ref(null);//副产品入库表格ref
  const instoreObjContainerTableRef = ref(null);//批次表格ref
  const byproductFormRef = ref(null);//副产品表单ref

  const instoreObj = reactive({
    dialogVisible: false,
    tabObj: { container: 'containerInfo', byproduct: 'byproduct', },
    // 表单
    form: {
      containerid: '',
      containername: '',
      productid: '',
      productname: '',
      productdesc: '',
      workflowstepname: '',
      workflowstepid: '',
      workflowid: '',
      mfgordername: '',
      qty: 0,
      lossqty: 0,//报废数
      passqty: 0,//合格数
      submitqty: 0,//提交数
      onceQualifiedNum: 0,//一次交检合格数
      qualityPolicyNumber: 0,//质保单数量
      instoreType: '正常入库',//入库类型
      originalFactorycode: '',//生产分厂
      entrustFactorycode: '',//委托单位
      stockLocation: '',//库存位置
      replaceMaterialNumber: '',//待料单号
      productfamily: '',//机型
      zlpNum: '',//炉批次顺序号
      notes: '',//备注
      zbhgdh: '',//不合格品审理单号
      oilSealDate: '',//油封日期
      oilPeriod: '',//油封周期
      allsetMsg: '',//配套发送信息
      allsetProductname: '',//配套零件号
      allsetContainername: '',//配套批次号
    },
    dataList: [],//副产品表格数据
    containerList: [],//单价单卡表格数据
    factoryList: [],
    stockLocationList: [],//库存位置
    // 表单校验
    formRules: {
      productfamily: [
        { required: true, message: '【机型】不能为空', trigger: 'blur' },
      ],
      stockLocation: [
        { required: true, message: '请选择【库存位置】', trigger: 'blur' },
      ],
      qualityPolicyNumber: [
        { required: true, message: '【质保单数量】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ],
      submitqty: [
        { required: true, message: '【提交数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ],
      passqty: [
        { required: true, message: '【合格数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ],
      lossqty: [
        { required: true, message: '【报废数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ],
      onceQualifiedNum: [
        { required: true, message: '【一次交检合格数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ]
    },
    // 副产品维护表单
    byproductForm: {
      materialNo: '',//物料编号
      submitNum: 0,//提交数
      qualifiedNum: 0,//合格数
      lossNum: 0,//报废数
      onceQualifiedNum: 0,//一次交检合格数
      qualityPolicyNumber: 0,//质保单数
    },
    // 副产品维护校验规则
    byproductFormRules: {
      materialNo: [
        { required: true, message: '【物料编号】不能为空', trigger: 'blur' },
      ],
      submitNum: [
        { required: true, message: '【提交数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ],
      qualifiedNum: [
        { required: true, message: '【合格数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ],
      lossNum: [
        { required: true, message: '【报废数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ],
      onceQualifiedNum: [
        { required: true, message: '【一次交检合格数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ],
      qualityPolicyNumber: [
        { required: true, message: '【质保单数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ]
    }
  });

  // 自定义校验规则
  function validator(rule, value, callback) {
    if (/^\d+$/.test(value)) {
      callback();
    } else {
      callback(new Error('只能输入整数'));
    }
  }

  // 查询获取ERP库存位置
  async function getERPInStoreLocationList() {
    const { data } = await useFetch({
      url: `${baseAPI}?actions=getERPInStoreLocationList`,
      data: { type: 'getERPInStoreLocationList' }
    });
    return data.value;
  }

  // 初始化数据
  async function initInstoreDialogData(currentSelectContainer, selectionRows, userInfo) {
    instoreObj.dialogVisible = true;
    currentUserInfo = userInfo.value;
    instoreObj.containerList = [];//先清空单价单卡表格数据
    instoreObj.factoryList = await getFactoryListByCode({ factoryCode: '600|601|602|603|607|608|609' });//查询分厂list
    instoreObj.stockLocationList = await getERPInStoreLocationList();//查询ERP库存列表

    const { workflowstepname, productid, productname, productdescription, workflowstepid, workflowid } = currentSelectContainer;
    const {
      containername, qty,
      containerid, mfgordername, familylistnames,
    } = selectionRows[0];

    instoreObj.form.containerid = containerid;
    instoreObj.form.containername = containername;
    instoreObj.form.productname = productname;
    instoreObj.form.productid = productid;
    instoreObj.form.productdesc = productdescription;
    instoreObj.form.workflowstepid = workflowstepid;
    instoreObj.form.workflowstepname = workflowstepname;
    instoreObj.form.mfgordername = mfgordername;
    instoreObj.form.qty = qty;
    instoreObj.form.productfamily = familylistnames;
    instoreObj.form.originalFactorycode = currentUserInfo.factorycode;
    instoreObj.form.entrustFactorycode = currentUserInfo.factorycode;
    instoreObj.form.workflowid = workflowid;
    // 库位位置默认选择第一个
    if (instoreObj.stockLocationList.length > 0) {
      instoreObj.form.stockLocation = instoreObj.stockLocationList[0].erpinstorelocatiname;
    }
    for (const i of selectionRows) {
      instoreObj.containerList.push({
        id: '',
        containerid: i.containerid,
        containername: i.containername,
        containertype: i.containertype,
        productfamily: '',
        qualityPolicyNumber: '',
        replaceMaterialNumber: '',
        zlpNum: '',
        instoreType: '',
        originalFactorycode: '',
        entrustFactorycode: '',
        stockLocation: '',
        notes: ''
      });
    }

    instoreObjContainerTableRef.value.toggleAllSelection();//批次表格数据默认全选
  }

  // 【确认】按钮点击
  async function handleInstoreConfirmClick() {
    const selections = instoreObjContainerTableRef.value.getSelectionRows();
    if (selections.length === 0) { return ElMessage({ type: 'error', message: `请勾选批次`, grouping: true }); }
    try {
      await instoreObjFormRef.value.validate();
      const id = generateUUID();
      for (let i of selections) {
        Object.assign(i, { ...instoreObj.form }, { containername: i.containername, containerid: i.containerid }, { id });
      }
    } catch (error) {
      return;
    }
  }

  // 副产品表格【添加】按钮
  async function handleInstoreAddClick() {
    try {
      await byproductFormRef.value.validate();
      instoreObj.dataList.push({
        id: generateUUID(),
        ...instoreObj.byproductForm
      });
      instoreObjTableRef.value.toggleAllSelection();//勾选已有全部副产品行
      byproductFormRef.value.resetFields();//重置副产品维护表单
    } catch (error) {
      return;
    }
  }

  // 删除按钮
  function handleInstoreDeleteClick() {
    const selection = instoreObjTableRef.value.getSelectionRows();
    if (selection.length === 0) { return ElMessage({ type: 'error', message: `请勾选要删除的数据`, grouping: true }); }
    instoreObj.dataList = instoreObj.dataList.filter(i => !selection.some(m => m.id === i.id));
  }

  // 重置对话框数据
  function resetDialogData() {
    instoreObj.dataList = [];
    instoreObj.containerList = [];
    instoreObjFormRef.value.resetFields();//重置主表单
    byproductFormRef.value.resetFields();//重置副产品维护表单
  }

  // 【提交】按钮点击
  async function handleInstoreSubmitClick() {
    // 其他校验
    if (!await validate()) { return; }
    ElMessageBox.confirm(`你确认要提交吗?`, '确认', { type: 'warning' }).then(async () => {
      const selection = instoreObjContainerTableRef.value.getSelectionRows();
      const containerList = [];
      for (const i of selection) {
        if (i.instoreType === '副产品入库') {
          for (const j of instoreObj.dataList) {
            containerList.push({ ...i, ...j, productname: j.materialNo });
          }
        } else {
          containerList.push({ ...i, productname: instoreObj.form.productname });
        }
      }
      const { data, status: { msg } } = await useFetch({
        url: `${baseAPI}?actions=saveData`,
        data: {
          type: 'saveData',
          employeename: currentUserInfo.employeename,
          containerList,//入库批次信息
        }
      });
      if (data.value === true) {
        ElMessage({ type: 'success', message: `保存成功`, grouping: true });
        instoreObj.dialogVisible = false;
        resetDialogData();
        setTimeout(() => {
          // 刷新主界面
          location.reload();
        }, 3000);
      } else {
        ElMessage({ type: 'error', message: msg, grouping: true });
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消' });
    });
  }

  async function validate() {
    if (instoreObjContainerTableRef.value.getSelectionRows().length === 0) {
      ElMessage({ type: 'error', message: `请选择批次`, grouping: true });
      return false;
    }

    if (instoreObj.containerList.some(i => !i.id)) {
      ElMessage({ type: 'error', message: `请先录入批次入库信息`, grouping: true });
      return false;
    }

    const instoreTypeArr = Array.from(new Set(instoreObj.containerList.map(m => m.instoreType)));
    if (instoreTypeArr.length === 2) {
      ElMessage({ type: 'error', message: `【入库类型】不能同时存在多种状态`, grouping: true });
      return false;
    }

    if (instoreObj.dataList.length === 0 && instoreObj.containerList.filter(i => i.instoreType === '副产品入库').length > 0) {
      ElMessage({ type: 'error', message: `副产品入库请添加【物料编号】`, grouping: true });
      return false;
    }

    return true;
  }

  // 批次表格单元格blur事件
  function handleInstoreCellBlur(label, row) {
    const mapping = [
      { cellname: '合格数', fieldname: 'passqty' },
      { cellname: '报废数', fieldname: 'lossqty' },
      { cellname: '一次交检合格数', fieldname: 'onceQualifiedNum' },
      { cellname: '提交数', fieldname: 'submitqty' },
      { cellname: '质保单数量', fieldname: 'qualityPolicyNumber' },
    ];
    const { fieldname } = mapping.filter(i => i.cellname === label)[0];
    if (!/^\d+$/.test(row[fieldname])) {
      row[fieldname] = 0;
      ElMessage({ type: 'error', message: `【${label}】必须为整数`, grouping: true });
    }
  }

  return {
    instoreObj,
    instoreObjFormRef,
    instoreObjTableRef,//副产品入库表格ref
    byproductFormRef,//副产品维护表单ref
    instoreObjContainerTableRef,//单件单卡批次表格ref
    initInstoreDialogData,
    handleInstoreAddClick,
    handleInstoreDeleteClick,
    handleInstoreConfirmClick,//确认入库信息按钮
    handleInstoreSubmitClick,//【确认】按钮点击
    handleInstoreCellBlur,//批次表格单元格blur事件
  };
}